package com.ctrip.ibu.permissions.security.service.impl;


import com.ctrip.ibu.permissions.common.exception.BaseException;
import com.ctrip.ibu.permissions.security.dto.AuthDto;
import com.ctrip.ibu.permissions.security.dto.UserDto;
import com.ctrip.ibu.permissions.security.entity.User;
import com.ctrip.ibu.permissions.security.repository.UserRepository;
import com.ctrip.ibu.permissions.security.security.JwtUser;
import com.ctrip.ibu.permissions.security.service.AuthService;
import com.ctrip.ibu.permissions.security.util.JwtTokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * description
 *
 * @author r.shi 2020/02/26 15:46
 */
@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public Map<String, Object> login(String username, String password) {
        Authentication authentication = null;
        try {
            authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(username, password));
        } catch (AuthenticationException e) {
            throw new BaseException("Invalid username/password supplied", HttpStatus.UNPROCESSABLE_ENTITY);
        }
        SecurityContextHolder.getContext().setAuthentication(authentication);
        JwtUser userDetail = (JwtUser) authentication.getPrincipal();

         String accessToken = jwtTokenUtil.generateTokenWithHead(userDetail);

        UserDto userDto = new UserDto(userDetail);
        Map<String, Object> authInfo = new HashMap<String, Object>(2) {{
            put("token", accessToken);
            put("user", userDto);
        }};
        return authInfo;
    }


    @Override
    public void registry(AuthDto dto) {
        User user = new User();
        BeanUtils.copyProperties(dto, user);

        if (!userRepository.existsByUsername(user.getUsername())) {
            user.setPassword(passwordEncoder.encode(user.getPassword()));
            userRepository.save(user);
        } else {
            throw new BaseException("Username is already in use", HttpStatus.UNPROCESSABLE_ENTITY);
        }
    }

    @Override
    public void logout() {
        SecurityContextHolder.getContext().setAuthentication(null);
    }

    @Override
    public UserDto info() {
        JwtUser jwtUser = (JwtUser) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        UserDto permsUserDto = new UserDto(jwtUser);
        return permsUserDto;
    }


}
